package com.yzf.demo.demo.Thread;

/**
 * Created by 于占峰 on 2020/3/31/031.
 * 可见性演示
 */
public class VisableDemo {
    //stop对于main线程而言是不具有可见性的 ,因此下面线程并不能通过stop来停止
    //public static boolean stop = false;
    //加入volatile字段 使stop具有可见性
    public volatile static boolean stop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            int i = 0;
            while (!stop) {
                i++;
            }
            System.out.println("Result:" + i++);
        });
        thread.start();
        System.out.println("线程开始执行");
        Thread.sleep(1000);//使线程休眠阻塞 切换到mian的主线程
        stop = true;//主线程中修改stop
    }

}
